package com.usefullc.system.service.component;

import com.google.code.kaptcha.Producer;
import com.usefullc.common.enums.CheckCodeTypeEnum;
import com.usefullc.system.service.AbstractService;
import com.usefullc.common.util.secure.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author: Sampson
 * @date: 2018-12-19 14:31
 */
@Component
public class ImgCodeComponent extends AbstractService {

    @Autowired
    private SystemConfigComponent systemConfigComponent;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    public String getImgCode(Integer type,final String clientId){
        String code = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(code);
//        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
//        String imgCode = imgCodeComponent.getImgCode(SmsCodeTypeEnum.LOGIN.getCode(), UserTypeEnum.ADMIN.getCode(), deviceId);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            logger.error("write image failed",e);
        }
//        return WebResultBuilder.successResult(Base64.encode(os.toByteArray()));
        final String imgCode = Base64.encode(os.toByteArray());
        //
        CheckCodeTypeEnum smsCodeTypeEnum = CheckCodeTypeEnum.getByCode(type);
        String smsCodeKey = StringUtils.join(new Object[]{smsCodeTypeEnum.getCacheKey(), clientId}, "_");
        logger.info("smsCodeKey={}",smsCodeKey);
        String cacheValue = stringRedisTemplate.opsForValue().get(smsCodeKey);
        if (StringUtils.isNotEmpty(cacheValue)) {  //存在不用重复发送
            //
        }

        stringRedisTemplate.opsForValue().set(smsCodeKey,code, smsCodeTypeEnum.getExpireTime(), smsCodeTypeEnum.getTimeUnit());
        if (systemConfigComponent.isProd()) {  //生产环境才发送验证码
            new Thread(() -> {
                //String value = "%23code%23%3d"+imgCode;
                //TODO
                //存储操作
//                SmsServer.this.sendMsgJH(AppConstant.SMSTemplate.registerId,mobile,value,0);
            }).start();
        }
        return "data:image/jpg;base64,"+imgCode;
    }

}
